<template>
  <div v-loading="loading">
    <el-card :body-style="{padding:'10px'}" style="min-height: 680px;">
      <!-------------------------------按钮 ----------------------down------------------->
      <el-row :gutter="24" style="padding-bottom: 5px">
        <el-col :span="21">
          <el-button type="info" @click="form ={ entitys: [{}, {}, {}, {}, {}] }">新建</el-button>
          <el-button type="info" @click="copyBill">复制</el-button>
          <el-button type="primary" @click="open1 = true">选择产品</el-button>
          <el-button type="primary" @click="open = true;">选择质检项目</el-button>
          <el-button type="success" @click="saveEdit">保存</el-button>
        </el-col>
        <el-col :span="3">
          <el-button-group>
            <el-button type="primary" icon="el-icon-arrow-left" @click="toLast" />
            <el-button type="primary" icon="el-icon-arrow-right" @click="toNext" />
          </el-button-group>
        </el-col>
      </el-row>
      <!------------------------------按钮 ----------------------up ------------------->
      <div>
        <el-form ref="form" :model="form" :rules="rules">
          <el-descriptions border style="margin-bottom: 10px" size="mini">
            <el-descriptions-item label="产品编码" label-style="width:8%" content-style="width:20%">{{ form.cinvcode }}</el-descriptions-item>
            <el-descriptions-item label="产品名称" label-style="width:8%" content-style="width:20%">{{ form.cinvname }}</el-descriptions-item>
            <el-descriptions-item label="产品规格" label-style="width:8%" content-style="width:20%">{{ form.cinvstd }}</el-descriptions-item>
            <el-descriptions-item label="方案名称" label-style="width:8%" content-style="width:20%">
              <el-form-item prop="name" class="des-input">
                <el-input v-model="form.name" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="方案版本" label-style="width:8%" content-style="width:20%">
              <el-form-item prop="version" class="des-input">
                <el-input v-model="form.version" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="质检等级">
              <el-form-item prop="level" class="des-input">
                <el-select v-model="form.level" placeholder="请选择">
                  <el-option
                    v-for="item in levels"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              <el-form-item prop="remark" class="des-input">
                <el-input v-model="form.remark" />
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </el-form>
        <el-table
          :data="form.entitys"
          tooltip-effect="dark"
          border
          style="width: 100%;"
        >
          <el-table-column
            type="index"
            label="项次"
            width="50"
          />
          <el-table-column
            prop="quota.name"
            width="150px"
            label="指标名称"
          />
          <el-table-column
            prop="quota.basePlan.name"
            width="150px"
            label="测试项目"
          />
          <el-table-column
            width="140"
            prop="type"
            label="指标类型"
          >
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.type" size="small">
                <el-radio-button label="字符" />
                <el-radio-button label="数值" />
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column
            width="155"
            prop="strVal"
            label="标准字符值"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.strVal" :disabled="scope.row.type != '字符'" @blur="sum" />
            </template>
          </el-table-column>
          <el-table-column
            width="155"
            prop="miniVal"
            label="最小数值"
          >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.miniVal" :controls="false" :disabled="scope.row.type != '数值'" @blur="sum" />
            </template>
          </el-table-column>
          <el-table-column
            width="155"
            prop="stanVal"
            label="标准数值"
          >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.stanVal" :controls="false" :disabled="scope.row.type != '数值'" @blur="sum" />
            </template>
          </el-table-column>
          <el-table-column
            width="155"
            prop="maxVal"
            label="最大数值"
          >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.maxVal" :controls="false" :disabled="scope.row.type != '数值'" @blur="sum" />
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            prop="grade"
            label="允许质量限度"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.aql" placeholder="请选择">
                <el-option
                  v-for="item in aqls"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            prop="specs"
            label="规格"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.specs" />
            </template>
          </el-table-column>
          <el-table-column
            width="80"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="form.entitys.splice(scope.$index,1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!------------------------------ ---------------------up ----------------------------------------------------->
      <!-------------------------------form表单----------------------up ------------------->
    </el-card>
    <el-dialog :visible.sync="open" width="80%" :close-on-click-modal="false">
      <el-row :gutter="20" style="margin: 10px">
        <el-col :span="2">
          <el-button class="hand-btn" type="primary" @click="selSet">选择</el-button>
        </el-col>
        <el-col :span="6">
          <el-input v-model="planQuery.name" placeholder="指标名称" />
        </el-col>
        <el-col :span="6">
          <el-button class="hand-btn" type="primary" icon="el-icon-search" @click="planSearch">查询</el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loadingPlan"
        :data="planPage.content"
        tooltip-effect="dark"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
        />
        <el-table-column
          type="index"
          label="项次"
          width="50"
        />
        <el-table-column
          prop="basePlan.name"
          label="项目名称"
        />
        <el-table-column
          prop="name"
          label="指标名称"
        />
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="planQuery.pageIndex"
          :page-size="planQuery.pageSize"
          :total="planPage.totalElements"
          @current-change="handlePlanPageChange"
        />
      </div>
    </el-dialog>
    <!--------------------------------产品查询 down------------------------------------------------------>
    <el-dialog :visible.sync="open1" width="80%" :close-on-click-modal="false">
      <div style="display: flex">
        <el-input v-model="productQuery.code" style="width: 200px;margin-right: 10px" placeholder="产品编码" />
        <el-input v-model="productQuery.name" style="width: 200px;margin-right: 10px" placeholder="产品名称" />
        <el-button class="hand-btn" type="primary" icon="el-icon-search" @click="productSearch">查询</el-button>
      </div>
      <el-table
        v-loading="loadingProduct"
        :data="productPage.content"
        tooltip-effect="dark"
        border
        style="width: 100%;"
      >
        <el-table-column
          type="index"
          label="项次"
          width="50"
        />
        <el-table-column
          prop="cInvCode"
          label="产品编码"
        />
        <el-table-column
          prop="cInvName"
          label="产品名称"
        />
        <el-table-column
          prop="cInvStd"
          label="产品规格"
        />
        <el-table-column label="操作" width="90" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              class="hand-btn"
              size="mini"
              icon="el-icon-edit"
              @click="selTable(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="productPage.pageIndex"
          :page-size="productPage.pageSize"
          :total="productPage.totalElements"
          @current-change="handleProductPageChange"
        />
      </div>
    </el-dialog>
    <!--------------------------------产品查询 up------------------------------------------------------>
  </div>
</template>
<script>import { save } from '@/api/project'
import { get } from '@/api/project'
import { getNext } from '@/api/project'
import { getLast } from '@/api/project'
import { query as queryplan } from '@/api/baseQuota'
import { query as queryProduct } from '@/api/u8Product'
import { delbyid } from '@/api/project'
export default {
  name: 'Project',
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请输入方案名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入方案版本', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择质检水平', trigger: 'blur' }
        ]
      },
      active: 1,
      open: false,
      open1: false,
      selPlans: [],
      editVisible: true,
      planQuery: {
        pageIndex: 1,
        pageSize: 10,
        name: ''
      },
      productQuery: {
        pageIndex: 1,
        pageSize: 10,
        name: ''
      },
      page: {},
      planPage: {},
      productPage: {},
      form: { name: '', entitys: [{}, {}, {}, {}, {}] },
      levels: ['S-1', 'S-2', 'S-3', 'S-4', 'I', 'II', 'III'],
      grades: [0.25, 0.4, 0.65, 1.0, 1.5, 2.5, 4.0, 6.5, 10, 15, 25],
      aqls: ['A', 'B', 'C'],
      loading: false,
      loadingPlan: false,
      loadingProduct: false
    }
  },
  created() {
    if (this.$route.query.id) {
      this.getProject(this.$route.query.id)
    }
    this.planSearch()
    this.productSearch()
  },
  methods: {
    // 获取 easy-mock 的模拟数据
    getProject(id) {
      this.loading = true
      get(id).then(res => {
        this.loading = false
        this.form = res.data.data
      })
    },
    getPlan() {
      this.loadingPlan = true
      queryplan(this.planQuery).then(res => {
        this.loadingPlan = false
        this.planPage = res.data.page
      })
    },
    copyBill() {
      this.form.id = null
      for (const ent of this.form.entitys) {
        ent.id = null
      }
      this.form.entitys = JSON.parse(JSON.stringify(this.form.entitys))
      this.$message.success('复制成功')
    },
    getProduct() {
      this.loadingProduct = true
      queryProduct(this.productQuery).then(res => {
        this.loadingProduct = false
        this.productPage = res.data.page
      })
    },
    selSet() {
      if (this.form.entitys.length === 0) {
        for (const row of this.selPlans) {
          const data = { quotaId: row.id, quota: row, type: '字符', strVal: '' }
          this.form.entitys.push(data)
        }
      } else {
        for (const row of this.selPlans) {
          let being = true
          for (const ent of this.form.entitys) {
            if (!ent.quotaId) {
              this.form.entitys = []
              break
            }
            if (row.id === ent.quotaId) {
              being = false
              break
            }
          }
          if (being) {
            const data = { quotaId: row.id, quota: row, type: '字符', strVal: null, specs: null, grade: null }
            this.form.entitys.push(data)
          }
        }
      }
      this.open = false
    },
    selTable(row) {
      console.log(row)
      this.form.cinvcode = row.cInvCode
      this.form.cinvname = row.cInvName
      this.form.cinvstd = row.cInvStd
      this.open1 = false
    },
    handleSelectionChange(rows) {
      this.selPlans = rows
    },
    // 触发搜索按钮
    planSearch() {
      this.$set(this.planQuery, 'pageIndex', 1)
      this.getPlan()
    }, // 触发搜索按钮
    productSearch() {
      this.$set(this.productQuery, 'pageIndex', 1)
      this.getProduct()
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, 'pageIndex', 1)
      this.getData()
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(() => {
        delbyid(row.id).then(res => {
          this.$message.success('删除成功')
          this.getData()
        })
      })
        .catch(() => {
        })
    },
    // 多选操作
    delAllSelection() {
      const length = this.multipleSelection.length
      let str = ''
      this.delList = this.delList.concat(this.multipleSelection)
      for (let i = 0; i < length; i++) {
        str += this.multipleSelection[i].name + ' '
      }
      this.$message.error(`删除了${str}`)
      this.multipleSelection = []
    },
    // 保存编辑
    saveEdit() {
      if (!this.form.cinvcode) {
        this.$message.warning('未选择产品')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.validateEntity()) {
            this.loading = true
            save(this.form).then(res => {
              this.loading = false
              this.$message.success(res.message)
              this.editVisible = false
              this.$router.push({ path: 'projectEdit', query: { id: res.data.data.id }})
              if (this.$route.query.id) {
                this.getProject(this.$route.query.id)
              }
            })
          }
        } else {
          this.$message.warning('信息未填写完整')
        }
      })
    },
    add() {
      this.form = { entitys: [], baseProduct: {}}
      this.editVisible = true
    },
    // 分页导航
    handlePlanPageChange(val) {
      this.$set(this.planQuery, 'pageIndex', val)
      this.getPlan()
    },
    // 产品分页导航
    handleProductPageChange(val) {
      this.$set(this.productQuery, 'pageIndex', val)
      this.getProduct()
    },
    toNext() {
      getNext(this.$route.query.id).then(res => {
        this.$router.push({ path: 'projectEdit', query: { id: res.data.data }})
        if (this.$route.query.id) {
          this.getProject(this.$route.query.id)
        }
      })
    },
    toLast() {
      getLast(this.$route.query.id).then(res => {
        this.$router.push({ path: 'projectEdit', query: { id: res.data.data }})
        if (this.$route.query.id) {
          this.getProject(this.$route.query.id)
        }
      })
    },
    sum() {
      for (const item of this.form.entitys) {
        if (item.type === '字符') {
          if (item.strVal === null) {
            // this.$message.warning('请输入匹配字符')
          } else {
            item.miniVal = null
            item.stanVal = null
            item.maxVal = null
            item.specs = item.strVal
          }
        } else if (item.type === '数值') {
          console.log(item.stanVal)
          if (!item.stanVal) {
            if (item.maxVal && item.miniVal) {
              item.strVal === null
              item.specs = item.miniVal + '~' + item.maxVal
            } else {
              item.specs = ''
            }
          } else {
            if (item.maxVal && item.miniVal) {
              item.strVal === null
              item.specs = item.miniVal + '~' + item.stanVal + '~' + item.maxVal
            } else {
              item.specs = ''
            }
          }
          this.strVal = null
        }
      }
      this.form.entitys = JSON.parse(JSON.stringify(this.form.entitys))
    },
    validateEntity() {
      for (const item of this.form.entitys) {
        if (item.type === '字符' && item.strVal === null) {
          this.$message.warning('请输入匹配字符')
          return false
        } else if (item.type === '数值') {
          if (item.miniVal === null) {
            this.$message.warning('请输入最小值')
            return false
          } else if (item.maxVal === null) {
            this.$message.warning('请输入最大值')
            return false
          } else if ((item.stanVal === null || item.stanVal === 0)) {
            if (item.miniVal > item.maxVal) {
              this.$message.warning('数值填写大小错误')
              return false
            }
          } else if (item.miniVal > item.stanVal || item.stanVal > item.maxVal) {
            this.$message.warning('数值填写大小错误')
            return false
          }
        }
      }
      return true
    }
  }
}
</script>

<style scoped>
  .handle-box {
    margin: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    margin: 10px;
    width: 300px;
    display: inline-block;
  }
  .table {
    width: 100%;
    font-size: 14px;
  }
  .red {
    color: #ff0000;
  }
  .hand-btn {
    margin: 5px;
  }
  .des-input{
    height:10px;
  }
</style>
